import { api } from "@/api"
import { defineStore } from "pinia"
import { computed, ref } from "vue"
import { useAppStore } from "./app"

const useContactsStore = defineStore('contacts', () => {
  const app = useAppStore()
  const friends = ref([])
  const newFriends = ref([])
  const groups = ref([])
  // const app = useAppStore()
  const fridensLoading = ref(false)
  const groupsLoading = ref(false)
  const waitingConfirmRequests = computed(() => newFriends.value.filter(item => item.status === 0))

  let initData = false
  async function init() {
    initData = true
    await Promise.all([
      refreshFriends(),
      refreshNewFriends(),
      refreshGroups()
    ])
    initData = false
  }

  async function refreshFriends() {
    fridensLoading.value = true
    const { data } = await api.friends.list()
    fridensLoading.value = false
    if (!Array.isArray(data)) return

    friends.value = data.map(item => ({
      ...item,
      isFriend: true
    }))
  }

  async function refreshNewFriends() {
    const { data } = await api.friends.newList()
    if (!Array.isArray(data)) return
    if (data.length !== newFriends.value.length && !initData) {
      app.playNotice()
    }
    newFriends.value = data
  }

  async function refreshGroups() {
    groupsLoading.value = true
    const { GroupIdList } = await api.group.list({ Member_Account: app.accessToken })
    groupsLoading.value = false
    if (!Array.isArray(GroupIdList)) return

    groups.value = GroupIdList
  }

  function reset() {
    friends.value = []
    newFriends.value = []
    groups.value = []
  }

  return {
    init,
    friends,
    fridensLoading,
    newFriends,
    groupsLoading,
    groups,
    refreshFriends,
    refreshGroups,
    refreshNewFriends,
    waitingConfirmRequests,
    reset
  }
})

export default useContactsStore
